package com.xframe.common.core.service.command;

import com.xframe.common.core.constant.ErrorConstant;
import com.xframe.domain.CommandModel;
import com.xframe.common.core.dto.ErrorCode;
import com.xframe.common.core.exception.BusinessException;
import com.xframe.domain.ModelRepositoryFactory;
import com.xframe.domain.repository.SysBaseRepository;
import com.xframe.domain.role.IUserCredentials;
import com.xframe.domain.sys.SysModel;
import com.xframe.domain.sys.SysModelAct;
import com.xframe.xdal.core.annotation.XAction;
import com.xframe.xdal.core.exception.DalFrameException;
import com.xframe.xdal.core.util.StringUtil;
import com.xframe.xdal.core.util.XReflect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;

/**
 * 功能描述:创建默认的按钮
 *
 * @author xufeng
 * @version 1.0
 * 2022-09-26
 */
public class CreateDefActionProc extends BaseCommand{
    @Override
    public Object ProcCommand(CommandModel requestArgs, IUserCredentials userCredentials) throws BusinessException {
        try {
            if (StringUtil.isEmpty(requestArgs.getModelCode())) {
                throw new BusinessException(com.xframe.common.core.dto.ErrorCode.MODELID_NULL, ErrorConstant.MODELID_NULL_MSG);
            }
            SysModel sysModel = SysModel.getInstance(requestArgs.getModelCode());
            if (sysModel == null) {
                throw new BusinessException(ErrorCode.DB_RECORD_NOFIND,
                        StringUtil.format(ErrorConstant.DB_RECORD_NOFIND_MSG, requestArgs.getModelCode()));
            }
            List<SysModelAct> sysModelActs = SysModelAct.getDefActionList(sysModel);
            Annotation[] accessibleAnnotations = XReflect.getAccessibleAnnotations(sysModel.getModelDataType(), XAction.class);
            Integer sortNum = 50 ;
            for (Annotation accessibleAnnotation : accessibleAnnotations) {
                SysModelAct action = SysModelAct.createAction(sysModel, (XAction) accessibleAnnotation, sortNum);
                sortNum = sortNum + 10;
                sysModelActs.add(action);
            }
            SysBaseRepository repository = ModelRepositoryFactory.builder(SysModelAct.class);
            Method method = this.getMethodByName(repository.getClass(), "batchSave", Class.class, Collection.class);
            this.execRepository(repository, method, SysModelAct.class, sysModelActs);
            return "OK";
        } catch (BusinessException businessException) {
            throw businessException;
        } catch (DalFrameException exception) {
            throw new BusinessException(exception.getCode(), exception.getMessage());
        } catch (Exception exception) {
            throw new BusinessException(com.xframe.common.core.dto.ErrorCode.INTERNAL_SERVER_ERROR, exception.getMessage());
        }
    }

    @Override
    public String getBeanName() {
        return "CreateDefActionProc";
    }
}
